<script lang="ts" setup>
import axios from 'axios'
import { onMounted, ref, render } from 'vue'

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const data = ref(null)
const dataview = ref(null)

const loading = ref(true)

// scene camera renderer
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight - 100)

const geometry = new THREE.BoxGeometry(0.01, 0.01, 0.01)

// orbit controls

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.dampingFactor = 0.05
controls.enablePan = false

// 创建实例化网格
const count = 100 * 100 * 100
const instancedMesh = new THREE.InstancedMesh(
  geometry,
  new THREE.MeshBasicMaterial({ color: 0x00ff00 }),
  count,
)

const matrix = new THREE.Matrix4()

function getColorFromValue(value) {
    const green = new THREE.Color(0x00ff00);
    const red = new THREE.Color(0xff0000);
    return green.lerp(red, value);
} 

// 网格着色，from blue to red
for (let i = 0; i < count; i++) {
  const color = new THREE.Color()
  const randomValue = Math.random();
  color.set(getColorFromValue(randomValue))
  instancedMesh.setColorAt(i, color)
}

for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    for (let k = 0; k < 2; k++) {
      matrix.setPosition(new THREE.Vector3(i * 0.01, j * 0.01, k * 0.01))
      instancedMesh.setMatrixAt(i * 100 * 100 + j * 100 + k, matrix)
    }
  }
}

scene.add(instancedMesh)


const axesHelper = new THREE.AxesHelper(3)
scene.add(axesHelper)

camera.position.y = 1
camera.position.x = 1
camera.position.z = 5

onMounted(async () => {
  // const res = await axios.get('/0_data_SPE10.csv')
  // console.log(res)
  // data.value = res.data
  //   .split('\n')
  //   .slice(0, 10)
  //   .map((line) => line.split(','))

  dataview.value.appendChild(renderer.domElement)

  function animate() {
    requestAnimationFrame(animate)
    renderer.render(scene, camera)
  }
  animate()
})
</script>

<template>
  <div>
    <!-- {{ data }} -->
    <div ref="dataview"></div>
  </div>
</template>

<style lang="scss" scoped></style>
